<template>
  <div id="xlinkAutoModal">
    <!-- select Auto搜索 2018/3/7 11:44 zhangQ -->
    <Select ref="autoSelect" v-model="selectValue" filterable :placeholder="placeholder" remote clearable :width="width" :multiple="multiple"
            :remote-method="remoteMethod" :loading="loading">
      <template v-for="item in optionData">
        <Option :value="item[field]">{{ item[label] }}</Option>
      </template>
    </Select>
  </div>
</template>

<script>
  import _ from 'lodash'

  export default {
    name: 'index',
    data () {
      let loading = false
      let optionData = []
      let datas = { loading, optionData }
      return datas
    },
    // props: ['value', 'placeholder', 'width', 'className', 'List', 'keys', 'label', 'searchKeys'],
    props: {
      value: {},
      multiple: {
        type: Boolean,
        default: false
      },
      placeholder: {
        type: String,
        default: ''
      },
      width: {
        type: String,
        default: ''
      },
      dataList: {
        type: Array,
        default () {
          return []
        }
      },
      field: {
        type: String,
        default: ''
      },
      label: {
        type: String,
        default: ''
      },
      searchKeys: {
        type: String,
        default: ''
      },
      dropAll: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      selectValue: {
        get () {
          return this.value
        },
        set (val) {
          this.$emit('on-change', val)
          this.$emit('input', val)
        }
      }
    },
    methods: {
      remoteMethod (txt) {
        this.loading = true
        if (txt) {
          setTimeout(() => {
            this.loading = false
            let upTxt = txt.toUpperCase()
            let lowTxt = txt.toLowerCase()
            let fields = this.searchKeys.split(',')
            let resSource = _.filter(this.dataList, function (sourceItem) {
              return _.some(fields, (fieldItem) => {
                return (_.includes(sourceItem[fieldItem], upTxt) || _.includes(sourceItem[fieldItem], lowTxt))
              })
            })
            this.optionData = resSource
          }, 200)
        } else {
          setTimeout(() => {
            this.loading = false
            if (this.dropAll) {
              this.optionData = this.dataList
            } else {
              this.optionData = []
            }
          }, 200)
        }
      }
    },
    mounted () {
      if (this.multiple) {
        this.$watch(() => {
          return this.selectValue.length
        }, (newVal, oldVal) => {
          this.remoteMethod()
        })
      }
      if (this.dropAll) {
        this.optionData = this.dataList
      }
    },
    components: {}
  }
</script>

<style>
  #xlinkAutoModal .ivu-select-not-found {
    display: none;
  }
</style>
